import cv2
import mediapipe as mp
import time
import HandTrackingModule as htm
import os

wCam , hCam = 640, 480
# 打开摄像头快，但是帧数低
cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
# 打开摄像头慢，但是帧数高
# cap = cv2.VideoCapture(0)
# cap.set(3, wCam)
# cap.set(4, hCam)

folderPath = "FingerImages"
myList = os.listdir(folderPath)
# print(myList)
overlayList = []
for imPath in myList:
    image = cv2.imread(f"{folderPath}/{imPath}")
    # print(f"{folderPath}/{imPath}")
    overlayList.append(image)

pTime = 0
detector = htm.handDetector(detectionCon= 0.7)
tipId = [4, 8, 12, 16, 20]

while True:
    success, img = cap.read()
    img = detector.findHands(img)
    lmList = detector.findPosition(img, draw=False)
    if len(lmList) != 0:
        fingers = []
        # Thumb
        if lmList[tipId[0]][1] > lmList[tipId[0]-1][1]:
            fingers.append(1)
        else:
            fingers.append(0)

        # Fingers
        for id in tipId[1:]:
            if lmList[id][2] < lmList[id-2][2]:
                fingers.append(1)
            else:
                fingers.append(0)
        # print(fingers)
        totalFingers = fingers.count(1)
        print(totalFingers)

        h, w, c = overlayList[totalFingers].shape
        img[0:h,0:w] = overlayList[totalFingers]

        # cv2.rectangle(img, (20,225), (170,425), (0, 255, 0), cv2.FILLED)
        # cv2.putText(img, str(totalFingers), (45, 375), cv2.FONT_HERSHEY_PLAIN, 10,
        #             (255, 0, 0), 25)

    cTime = time.time()
    fps = 1 / (cTime - pTime)
    pTime = cTime
    cv2.putText(img, f"FPS : {int(fps)}", (480, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
    cv2.imshow("Image", img)



    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

